//
//  BaseRequest.m
//  BaseTdkc
//
//  Created by DavidHuang on 16/7/1.
//  Copyright © 2016年 黄栋炜. All rights reserved.
//

/**
 if ([responseObject[@"status"] integerValue] == 200) {
 NSLog(@"%@ = %@", urlStr, [NSString jsonStrWithData:responseObject]);
 success(responseObject);
 } else {
 NSLog(@"%@ = %@", urlStr, [NSString jsonStrWithData:responseObject]);
 NSError *wrong = [[NSError alloc] initWithDomain:responseObject[@"message"] code:[responseObject[@"status"] integerValue]  userInfo:responseObject];
 fail(wrong);
 }
 */
#import "BaseRequest.h"
#import "AFNetworking.h"
#import "NSString+Ext.h"
#import "Utility.h"
#import "UserDefault.h"

@implementation BaseRequest {
    AFHTTPRequestOperationManager *_requestManager;  
}
NSString *const key_Cookie = @"key_cookie";
static BaseRequest *_shareInstance = nil;
static dispatch_once_t onceToken;

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    dispatch_once(&onceToken, ^{
        _shareInstance = [super allocWithZone:zone];
    });
    return _shareInstance;
}

+ (instancetype)copyWithZone:(struct _NSZone *)zone
{
    return _shareInstance;
}

+ (instancetype)mutableCopyWithZone:(struct _NSZone *)zone
{
    return _shareInstance;
}

+ (BaseRequest *)shareInstance {
    if (_shareInstance == nil) {
        _shareInstance = [[BaseRequest alloc] init];
    }
    return _shareInstance;
}

- (instancetype)init {
    if (self == [super init]) {
        _requestManager = [AFHTTPRequestOperationManager manager];
        NSSet *set = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil,nil];
        _requestManager.responseSerializer.acceptableContentTypes = set;
    }
    return self;
}


- (void)sendRequestType:(RequestType)requestType Url:(NSString *)keyStr parameter:(NSDictionary *)parameter success:(void (^)(NSDictionary *source))success fail:(void (^)(NSError *error))fail {
        NSString *urlStr = nil;
    if (keyStr && keyStr.length > 0) {
         urlStr = [NSString stringWithFormat:@"%@/%@",KEY_BASE_URL, keyStr];
    }else {
        urlStr = [NSString stringWithFormat:@"%@",KEY_BASE_URL];
    }
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:key_Cookie] && ![[[NSUserDefaults standardUserDefaults] objectForKey:key_Cookie] isEqualToString:@""]) {
        [_requestManager.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] objectForKey:key_Cookie] forHTTPHeaderField:@"cookie"];
    }
    NSLog(@"url = %@, para = %@",urlStr, parameter);
    if (requestType == RequestTypePost) {
        [_requestManager POST:urlStr parameters:parameter success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            NSString *cookieValue = [[operation.response allHeaderFields] valueForKey:@"Set-Cookie"];
            if (![Utility isEmpty:cookieValue]) {
                DEFAULTS_INFO(cookieValue, key_Cookie);
                DEFAULTS_SYNCHRONIZE;
            }
            if (responseObject) {
                NSLog(@"result = %@",[NSString jsonStrWithData:responseObject]);
                success(responseObject);
            }
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
            NSLog(@"wrong ==== %@",error);
            fail(error);
        }];
    } else if (requestType == RequestTypeGet) {
        [_requestManager GET:urlStr parameters:parameter success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            NSString *cookieValue = [[operation.response allHeaderFields] valueForKey:@"Set-Cookie"];
            if (cookieValue) {
                DEFAULTS_INFO(cookieValue, key_Cookie);
                DEFAULTS_SYNCHRONIZE;
            }
            if (responseObject) {
                NSLog(@"result = %@",[NSString jsonStrWithData:responseObject]);
                success(responseObject);
            }
            
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
            NSLog(@"wrong ==== %@",error);
            fail(error);
        }];
    }
}

- (void)uploadFileWithUrlStr:(NSString *)urlStr parameter:(NSDictionary *)parameter Data:(NSData *)fileData success:(void (^)(NSDictionary *source))success fail:(void (^)(NSError *error))fail {
    if ([[NSUserDefaults standardUserDefaults] objectForKey:key_Cookie] && ![[[NSUserDefaults standardUserDefaults] objectForKey:key_Cookie] isEqualToString:@""]) {
        [_requestManager.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] objectForKey:key_Cookie] forHTTPHeaderField:@"cookie"];
    }
    NSString *postUrl = [NSString stringWithFormat:@"%@/%@",KEY_BASE_URL,urlStr];
    NSLog(@"upload image = %@",postUrl);
    [_requestManager POST:postUrl parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:fileData name:@"myfiles" fileName:@"image.jpg" mimeType:@"image/png"];
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        if (responseObject) {
            NSLog(@"result = %@",[NSString jsonStrWithData:responseObject]);
            success(responseObject);
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        NSLog(@"upload iamge error ====== %@",error);
        fail(error);
    }];
}


- (void)startMultiPartUploadTaskWithURL:(NSString *)url
                            imagesArray:(NSArray *)images
                      parameterOfimages:(NSString *)parameter
                         parametersDict:(NSDictionary *)parameters
                       compressionRatio:(float)ratio
                           succeedBlock:(void(^)(id operation, id responseObject))succeedBlock
                            failedBlock:(void(^)(id operation, NSError *error))failedBlock
                    uploadProgressBlock:(void(^)(float uploadPercent,long long totalBytesWritten,long long totalBytesExpectedToWrite))uploadProgressBlock {
    
    if (images.count == 0) {
        NSLog(@"上传内容没有包含图片");
        return;
    }
    for(NSInteger i = 0 ; i<images.count; i++){
        if (![images[i] isKindOfClass:[UIImage class]]) {
            NSLog(@"images中第%d个元素不是UIImage对象",i+1);
            return;
        }
    }
    NSString *urlStr = [NSString stringWithFormat:@"%@/%@",KEY_BASE_URL, url];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:key_Cookie] && ![[[NSUserDefaults standardUserDefaults] objectForKey:key_Cookie] isEqualToString:@""]) {
        [_requestManager.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] objectForKey:key_Cookie] forHTTPHeaderField:@"cookie"];
    }
    AFHTTPRequestOperation *operation = [_requestManager POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        int i = 0;
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy年MM月dd日"];
        NSString *dateString = [formatter stringFromDate:date];
        for(UIImage *image in images){
            NSString *fileName = [NSString stringWithFormat:@"%@%d.png",dateString, i];
            NSData *imageData ;
            if (ratio > 0.0 && ratio < 1.0) {
                imageData = UIImageJPEGRepresentation(image, ratio);
            }else {
                imageData = UIImageJPEGRepresentation(image, 1.0);
            }
            
            [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"%@%@",fileName,@(i)] fileName:fileName mimeType:@"image/jpg/png/jpeg"];
            i++;
        }
        
        
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        succeedBlock(operation,responseObject);
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        failedBlock(operation,error);
    }];
    
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        CGFloat percent = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
        uploadProgressBlock(percent,totalBytesWritten,totalBytesExpectedToWrite);
    }];
    
}
@end
